package com.regentsoft.cloudback.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.regentsoft.cloudback.exception.JsonFormatException;

import java.io.IOException;

public class JsonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static String toJsonStr(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new JsonFormatException("JSON格式化错误：" + obj.getClass().getSimpleName(), e);
        }
    }

    public static <T> T toObject(String jsonStr, Class<T> c) {
        try {
            return mapper.readValue(jsonStr, c);
        } catch (IOException e) {
            throw new JsonFormatException("JSON格式化错误：" + c.getSimpleName(), e);
        }
    }

}
